package com.northone.statistics.activity;

import java.util.Calendar;

import com.northone.statistics.MyApplication;
import com.northone.statistics.R;
import com.northone.statistics.database.SaintDataBaseHelper;
import com.northone.statistics.utils.ToastUtil;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddSaintActivity extends Activity implements OnClickListener {
	private RadioGroup rg_sex, rg_home, rg_family, rg_gohome, rg_homeopen;
	private EditText et_name, et_number, et_wechat, et_Email, et_native, et_old_aklxy, et_remark;
	private Spinner sp_type, sp_marr;
	private Button btn_birthday, btn_baptism, btn_nativeTime;

	private String typeValue;
	private String marriage;

	private MyApplication application;
	// 左侧的返回按键 。
	private ImageView iv_back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addsaint);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);


		application = (MyApplication) getApplication();

		initView();
		initListener();
		initTitleBar();
	
		
	}

	/** 初始化View */
	private void initView() {
		
		et_name = (EditText) findViewById(R.id.et_name);
		rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
		btn_birthday = (Button) findViewById(R.id.btn_birthday);
		btn_baptism = (Button) findViewById(R.id.btn_baptism);
		et_number = (EditText) findViewById(R.id.et_number);
		et_wechat = (EditText) findViewById(R.id.et_wechat);
		et_Email = (EditText) findViewById(R.id.et_Email);
		sp_type = (Spinner) findViewById(R.id.sp_type);
		sp_marr = (Spinner) findViewById(R.id.sp_marr);
		et_native = (EditText) findViewById(R.id.et_native);
		rg_home = (RadioGroup) findViewById(R.id.rg_home);
		rg_family = (RadioGroup) findViewById(R.id.rg_family);
		rg_homeopen = (RadioGroup) findViewById(R.id.rg_homeopen);
		rg_gohome = (RadioGroup) findViewById(R.id.rg_gohome);
		et_old_aklxy = (EditText) findViewById(R.id.et_old_aklxy);
		btn_nativeTime = (Button) findViewById(R.id.btn_nativeTime);
		et_remark = (EditText) findViewById(R.id.et_remark);
	}

	/** 初始化监听器 。 */
	private void initListener() {
		btn_birthday.setOnClickListener(this);
		btn_baptism.setOnClickListener(this);
		btn_nativeTime.setOnClickListener(this);

		sp_type.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				typeValue = getResources().getStringArray(R.array.saintType)[position];
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		sp_marr.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				marriage = getResources().getStringArray(R.array.marriage)[position];
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}

	/** 初始化标题栏 。 */
	private void initTitleBar() {
		iv_back = (ImageView) findViewById(R.id.iv_lefticon);
		TextView tv_title = (TextView) findViewById(R.id.tv_title);
		Button btn_submit = (Button) findViewById(R.id.btn_submit);

		iv_back.setImageResource(R.drawable.addsaint_titlebar_back_selector);
		btn_submit.setVisibility(View.VISIBLE);
		btn_submit.setOnClickListener(this);
		iv_back.setOnClickListener(this);
		tv_title.setText("添加圣徒");
		btn_submit.setText("确定");

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_submit:
			addSaintInfoToDB();
			break;
		case R.id.iv_lefticon:
			finish();
			break;
		case R.id.btn_birthday:
		case R.id.btn_baptism:
		case R.id.btn_nativeTime:
			choiceDateDialog(v);
			break;
		default:
			break;
		}
	}

	/** 弹出选择日期的对话框 。 */
	private void choiceDateDialog(final View v) {
		Calendar calendar = Calendar.getInstance();
		new DatePickerDialog(AddSaintActivity.this, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				switch (v.getId()) {
				case R.id.btn_birthday:
					btn_birthday.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
					break;
				case R.id.btn_baptism:
					btn_baptism.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
					break;
				case R.id.btn_nativeTime:
					btn_nativeTime.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
					break;
				default:
					break;
				}
			}
		}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
	}

	/** 添加圣徒的信息到数据库中 。 */
	private void addSaintInfoToDB() {
		ContentValues values = new ContentValues();
		String name = et_name.getText().toString();
		String phoneNumber = et_number.getText().toString();
		String wechatNumber = et_wechat.getText().toString();
		String baptismDate = btn_baptism.getText().toString();
		if (TextUtils.isEmpty(name)) {
			ToastUtil.showToast(this, "请输入圣徒的信息 !");
			return;
		}
		if (TextUtils.isEmpty(phoneNumber)) {
			ToastUtil.showToast(this, "请输入圣徒的信息 !");
			return;
		}else if (!phoneNumber.matches("1[358]\\d{9}")) {
			ToastUtil.showToast(this, "请输入正确的手机号码 !");
			return;
		}
		if (isSameSaint(name, phoneNumber)) {
			Toast.makeText(this, "您输入的圣徒已经存在 !", Toast.LENGTH_LONG).show();
			return;
		}
		values.put("name", name);
		values.put("sex", rg_sex.getCheckedRadioButtonId() == R.id.sex_male ? "弟兄" : "姊妹");
		values.put("birthday", "出生日期:" + btn_birthday.getText().toString());
		if (baptismDate.equals(getResources().getString(R.string.selectDate))) {
			values.put("baptism", "未填写得救日期");
		} else {
			values.put("baptism", baptismDate + "得救");
		}
		values.put("phone", "电话:" + Long.parseLong(phoneNumber));
		if (TextUtils.isEmpty(wechatNumber)) {
			values.put("wechat", "");
		} else {
			values.put("wechat", "微信:" + wechatNumber);
		}
		values.put("Email", "E-mail:" + et_Email.getText().toString());
		values.put("type", typeValue);
		values.put("marriage", marriage);
		values.put("native", "籍贯:" + et_native.getText().toString());
		values.put("remark", "备注:" + et_remark.getText().toString());

		application.database.insert(SaintDataBaseHelper.TABLE_NAME_BASE, null, values);

		ContentValues cv = new ContentValues();
		cv.put("name", name);
		cv.put("allhome", rg_home.getCheckedRadioButtonId() == R.id.rb_yes ? "全家得救" : "未全家得救");
		cv.put("family", rg_family.getCheckedRadioButtonId() == R.id.rb_yes1 ? "基督徒家庭" : "非基督徒家庭");
		cv.put("openhome", rg_homeopen.getCheckedRadioButtonId() == R.id.rb_yes2 ? "家打开" : "家没有打开");
		cv.put("oldaklxy", et_old_aklxy.getText().toString());
		cv.put("nativetime", btn_nativeTime.getText().toString());
		cv.put("gohome", rg_gohome.getCheckedRadioButtonId() == R.id.rb_yes3 ? "离京" : "北京");

		application.database.insert(SaintDataBaseHelper.TABLE_NAME_EXTEND, null, cv);

		setResult(RESULT_OK);

		finish();
	}

	/** 判断是否为相同的圣徒，也就是数据库中已经存在的圣徒。 */
	private boolean isSameSaint(String name, String phoneNumber) {
		Cursor cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_BASE, null, null, null, null, null, null);
		boolean flag = cursor.moveToFirst();
		while (flag) {
			String dbSaintName = cursor.getString(cursor.getColumnIndex("name"));
			String dbSaintPhone = cursor.getString(cursor.getColumnIndex("phone"));
			if (dbSaintName.equals(name) && dbSaintPhone.equals("电话:" + phoneNumber)) {
				// 有相同的人，返回true。
				return true;
			}
			flag = cursor.moveToNext();
		}
		cursor.close();
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// application.database.close();
	}

}
